package com.wanggsx.library.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Vibrator;
import android.provider.MediaStore;

import com.wanggsx.library.util.fun.media.player.SoundPoolUtil;
import com.wanggsx.library.util.fun.media.player.VoicePlayerListener;
import com.wanggsx.library.util.fun.media.player.VoicePlayerManager;
import com.wanggsx.library.util.fun.media.recoder.VoiceRecoderManger;
import com.wanggsx.library.util.fun.media.recoder.VoiceRecorderListener;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by wanggsx on 15/12/9.
 */
public final class UtilsMedia {

    private static VoiceRecoderManger voiceRecoderManger = null;
    private static VoicePlayerManager voicePlayerManager = null;

    public static String startRecordVoice(boolean isAutoStop, long stopInMillSeconds, VoiceRecorderListener listener) {
        if (voiceRecoderManger == null) {
            voiceRecoderManger = new VoiceRecoderManger();
        }
        return voiceRecoderManger.startRecordVoice(isAutoStop, stopInMillSeconds, listener);
    }

    public static void stopVoiceRecoding() {
        if (voiceRecoderManger != null) {
            voiceRecoderManger.stopRecordVoice();
            voiceRecoderManger = null;
        }
    }

    public static boolean startPlayVoice(String strFile, VoicePlayerListener listener) {
        if (voicePlayerManager == null) {
            voicePlayerManager = new VoicePlayerManager();
        }
        return voicePlayerManager.playVoiceFile(strFile, listener);
    }

    public static boolean startPlayVoiceUrl(Context context, String url, VoicePlayerListener listener) {
        if (voicePlayerManager == null) {
            voicePlayerManager = new VoicePlayerManager();
        }
        return voicePlayerManager.playVoiceUrl(context, url, listener);
    }

    public static void stopPlayVoice(VoicePlayerListener listener) {
        if (voicePlayerManager != null) {
            voicePlayerManager.stopVoicePlaying(listener);
        }
    }


    /**
     * 播放声音 注意：如果需要调用此方法，请先在AppInit中调用SoundPoolUtil.loadVoice方法进行声音文件的初始化
     * 其中声音文件放到raw目录下面
     *
     * @param ctx
     * @param soundId 此id定义在CST类中
     * @param number  循环次数：0表示不循环，-1表示无限循环
     */
    public static void playRawSoundAfterInit(Context ctx, int soundId, int number) {
        SoundPoolUtil.playSound(ctx, soundId, 0);
    }

    /**
     * 其中声音文件放到raw目录下面
     *
     * @param context Context对象
     * @param res     raw文件Id
     */
    public static void playRawSound(Context context, int res) {
        SoundPoolUtil.playMedia(context, res);
    }


    /**
     * 震动
     *
     * @param context
     * @param millsecond
     */
    public static void playVibrate(Context context, long millsecond) {
        Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(millsecond);
    }

    /**
     * 获取语音文件的长度
     *
     * @param filePath
     * @return
     */
    public static int getDurationTime(String filePath) {   //使用此方法可以直接在后台获取音频文件的播放时间，而不会真的播放音频
        MediaPlayer player = new MediaPlayer();  //首先你先定义一个mediaplayer
        try {
            player.setDataSource(filePath);  //String是指音频文件的路径
            player.prepare();        //这个是mediaplayer的播放准备 缓冲

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {//监听准备

            @Override
            public void onPrepared(MediaPlayer player) {
                int size = player.getDuration();
                String timelong = size / 1000 + "''";

            }
        });
        double size = player.getDuration();//得到音频的时间
        int timelong1 = (int) Math.ceil((size / 1000));//转换为秒 单位为''
        player.stop();//暂停播放
        player.release();//释放资源
        return timelong1;  //返回音频时间
    }

    /**
     * 拍照
     * 在OnActivityResult中调用：getImagePathAfter()
     *
     * @param activity
     * @param path
     * @param reqCode
     */
    public static void getImageFromCamera(Activity activity, String path, int reqCode) {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        if (path == null) {
            path = UtilsFile.getAutoFileDirectory() + UUID.randomUUID().toString() + ".png";
        }
        Uri uri = Uri.fromFile(new File(path));
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        activity.startActivityForResult(intent, reqCode);
    }

    /**
     * 从相册获取图片
     * 在OnActivityResult中调用：getImagePathAfter()
     *
     * @param activity
     * @param reqCode
     */
    public static void getImageFromGallery(Activity activity, int reqCode) {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        activity.startActivityForResult(intent, reqCode);
    }

    /**
     * 通过onActivityResult返回的Intent获取图片路径
     *
     * @param activity
     * @param resultIntent
     * @return
     */
    public static String getImagePathAfter(Activity activity, Intent resultIntent) {
        if (resultIntent != null) {
            Uri uri = resultIntent.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = null;
            cursor = activity.getContentResolver().query(uri,
                    filePathColumn, null, null, null);
            if (cursor != null) {
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String picturePath = cursor.getString(columnIndex);
                cursor.close();
                return picturePath;
            } else {
                String picPath = uri.getPath();
                return picPath;
            }
        }
        return null;
    }


}
